package com.kws.system.controller;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.util.StringUtil;
import com.kws.common.core.constant.SecurityConstants;
import com.kws.common.core.enums.ChannelEnum;
import com.kws.common.core.utils.HttpClientUtil;
import com.kws.system.api.domain.QueryAccessTokenInfo;
import com.kws.system.api.domain.SysDept;
import com.kws.system.api.domain.SysRole;
import com.kws.system.domain.SysMenu;
import com.kws.system.domain.info.QueryDictDataInfo;
import com.kws.system.domain.info.QueryMenuInfo;
import com.kws.system.domain.info.QueryMenuTreeInfo;
import com.kws.system.domain.po.MerchantDeptPo;
import com.kws.system.domain.vo.CreateUserRq;
import com.kws.system.domain.vo.QueryUserInformationInfo;
import com.kws.system.domain.vo.QueryUserRq;
import com.kws.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.kws.common.core.domain.R;
import com.kws.common.core.utils.StringUtils;
import com.kws.common.core.utils.poi.ExcelUtil;
import com.kws.common.log.annotation.Log;
import com.kws.common.log.enums.BusinessType;
import com.kws.common.security.annotation.InnerAuth;
import com.kws.common.security.annotation.RequiresPermissions;
import com.kws.common.security.utils.SecurityUtils;
import com.kws.system.api.domain.SysUser;
import com.kws.system.api.model.LoginUser;

/**
 * 用户信息
 * 
 * @author zhangyh
 */
@RestController
@RequestMapping("/user")
@Api(value = "sysUser", tags = "用户信息管理模块")
public class SysUserController
{
    private static final Logger logger = LoggerFactory.getLogger(SysUserController.class);
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private ISysPermissionService permissionService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private SysCompanyMessageService sysCompanyMessageService;

    // 查询微信用户信息地址
    private static final String QUERY_USER_URL = "https://api.weixin.qq.com/sns/userinfo";


    @ApiOperation("根据手机号注册用户")
    @GetMapping("/register/user/byPhone")
    public R registerUserUser(@RequestParam String phone,@RequestParam String userType,@RequestParam String password, @RequestHeader(SecurityConstants.FROM_SOURCE) String source){
        return userService.registerUserUser(phone,password,userType);
    }


    /**
     * 获取用户列表
     */
//    @RequiresPermissions("system:user:list")
    @PostMapping("/list")
    @ApiOperation(value = "用户列表查询")
    public R<Page<SysUser>> list(@RequestBody QueryUserRq rq)
    {
        Page<SysUser> pageInfo = userService.queryUserPage(rq);
        return R.ok(pageInfo);
    }

    @ApiOperation("根据类型查询对应用户")
    @GetMapping("/query/userList")
    public R<List<SysUser>> queryUserListByType(@RequestParam String userType){
        List<SysUser> userList = userService.queryUserListByType(userType);
        return R.ok(userList);
    }

//    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
////    @RequiresPermissions("system:user:export")
//    @PostMapping("/export")
//    @ApiOperation(value = "用户列表导出")
//    public void export(HttpServletResponse response, @RequestBody SysUser user)
//    {
//        List<SysUser> list = userService.selectUserList(user);
//        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
//        util.exportExcel(response, list, "用户数据");
//    }

//    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
////    @RequiresPermissions("system:user:import")
//    @PostMapping("/importData")
//    @ApiOperation(value = "用户批量导入")
//    public R importData(MultipartFile file, boolean updateSupport) throws Exception
//    {
//        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
//        List<SysUser> userList = util.importExcel(file.getInputStream());
//        String operName = SecurityUtils.getUsername();
//        String message = userService.importUser(userList, updateSupport, operName);
//        return R.ok(message);
//    }

//    @PostMapping("/importTemplate")
//    @ApiOperation(value = "用户批量导入模板")
//    public void importTemplate(HttpServletResponse response) throws IOException
//    {
//        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
//        util.importTemplateExcel(response, "用户数据");
//    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/info/{username}")
    public R<LoginUser> info(@PathVariable("username") String username)
    {
        QueryDictDataInfo dataInfo = dictDataService.selectDictDataById(11111111111L);
        if(dataInfo == null || !StringUtils.equals("1",dataInfo.getDictValue())){
            return R.fail("使用权限已过期，请联系管理员续期");
        }

        SysUser sysUser = userService.selectUserByUserName(username);
        if (StringUtils.isNull(sysUser))
        {
            return R.fail("用户名或密码错误");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setRoles(roles);
        /*if (null != sysUser) {
            //根据用户ID查询企业信息
            SysCompanyMessage companyMessage = sysCompanyMessageService.queryCompanyMessageByUserId(sysUser.getUserId());
            if (null != companyMessage) {
                sysUserVo.setCompanyId(companyMessage.getId());
            }
        }*/
        sysUserVo.setPermissions(permissions);
        return R.ok(sysUserVo);
    }

    @GetMapping("/getUserByPhone/{phone}")
    @ApiOperation("根据手机号查询用户信息")
    R<LoginUser> checkUserByUserPhone(@PathVariable("phone") String phone, @RequestHeader(SecurityConstants.FROM_SOURCE) String source){
        SysUser sysUser = userService.selectUserByUserPhone(phone);
        if (StringUtils.isNull(sysUser))
        {
            return R.fail("用户名或密码错误");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setRoles(roles);
        /*if (null != sysUser) {
            //根据用户ID查询企业信息
            SysCompanyMessage companyMessage = sysCompanyMessageService.queryCompanyMessageByUserId(sysUser.getUserId());
            if (null != companyMessage) {
                sysUserVo.setCompanyId(companyMessage.getId());
            }
        }*/
        sysUserVo.setPermissions(permissions);
        return R.ok(sysUserVo);
    }


    @PostMapping("/query/openId")
    @ApiOperation("校验用户信息")
    R<LoginUser> checkUserByAppCode(@RequestBody QueryAccessTokenInfo info){
        SysUser sysUser = userService.queryUserByOpenId(info.getOpenid());
//        if (null != sysUser && ChannelEnum.CHANNEL_SHIFT.getKey().equals(info.getChannel()))
//        {
//            Map<String, String> map = new HashMap<>();
//            map.put("access_token", info.getAccess_token());
//            map.put("openid", info.getOpenid());
//            map.put("lang", "zh_CN");
//            String userInformation = HttpClientUtil.doGet(QUERY_USER_URL, map);
//            if (StringUtil.isNotEmpty(userInformation)) {
//                QueryUserInformationInfo informationInfo = JSONUtil.toBean(userInformation, QueryUserInformationInfo.class);
//                logger.info("调用腾讯获取用户信息返回结果:{}" + JSONUtil.parse(informationInfo));
//                sysUser.setNickName(informationInfo.getNickname());
//                sysUser.setSex(informationInfo.getSex());
//                sysUser.setAvatar(informationInfo.getHeadimgurl());
//                if (info.getChannel().equals(ChannelEnum.CHANNEL_USER_MIN.getKey())){
//                    sysUser.setUserOpenId(informationInfo.getOpenid());
//                }
//                sysUser.setStatus("0");
//                sysUser.setDelFlag("0");
//                sysUser.setUpdateTime(new Date());
//                sysUser.setCreateTime(new Date());
//                userService.registerUser(sysUser);
//            }
//        }
        LoginUser sysUserVo = new LoginUser();
        if (null != sysUser){
            // 角色集合
            Set<String> roles = permissionService.getRolePermission(sysUser);
            // 权限集合
            Set<String> permissions = permissionService.getMenuPermission(sysUser);
            sysUserVo.setSysUser(sysUser);
            sysUserVo.setRoles(roles);
            sysUserVo.setPermissions(permissions);

        }
        return R.ok(sysUserVo);
    }

    @GetMapping("/bind/userPhone/byOpenId")
    R<LoginUser> bindUserOpenId(@RequestParam("openId") String openId, @RequestParam("phone")  String phone,@RequestParam("channel") String channel, @RequestHeader(SecurityConstants.FROM_SOURCE) String inner){
        LoginUser sysUserVo = new LoginUser();
        SysUser sysUser = userService.selectUserByUserPhone(phone);
        if (null != sysUser){
            if (channel.equals(ChannelEnum.CHANNEL_SHIFT.getKey())){
                sysUser.setUserOpenId(openId);
            }else if (channel.equals(ChannelEnum.CHANNEL_MERCHANT_MIN.getKey())){
                sysUser.setMerchantAppletOpenId(openId);
            }else if (channel.equals(ChannelEnum.CHANNEL_SHIFT.getKey())){
                sysUser.setAccountOpenId(openId);
            }
            //绑定用户openId
            int i = userService.updateUser(sysUser);
            if (1 == i){
                // 角色集合
                Set<String> roles = permissionService.getRolePermission(sysUser);
                // 权限集合
                Set<String> permissions = permissionService.getMenuPermission(sysUser);
                sysUserVo.setSysUser(sysUser);
                sysUserVo.setRoles(roles);
                sysUserVo.setPermissions(permissions);
                return R.ok(sysUserVo);
            }else {
                return R.fail("未查询到用户信息");
            }
        }else {
            return R.fail("未查询到用户信息");
        }
    }


    /**
     * 注册用户信息
     */
//    @InnerAuth
    @PostMapping("/register")
    @ApiOperation("注册用户")
    public R<Boolean> register(@RequestBody SysUser sysUser)
    {
        //todo 添加验证码校验
        String username = sysUser.getUserName();
//        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser"))))
//        {
//            return R.fail("当前系统没有开启注册功能！");
//        }
        if (!userService.checkUserNameUnique(sysUser))
        {
            return R.fail("保存用户'" + username + "'失败，注册账号已存在");
        }
        return R.ok(userService.registerUser(sysUser));
    }

    /**
     *记录用户登录IP地址和登录时间
     */
    @PostMapping("/recordlogin")
    public R<Boolean> recordlogin(@RequestBody SysUser sysUser)
    {
        return R.ok(userService.updateUserProfile(sysUser));
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @ApiOperation(value = "获取当前登录用户信息")
    @GetMapping("getInfo")
    public R getInfo(HttpServletRequest request)
    {
        SysUser user = userService.selectUserById(SecurityUtils.getUserId());
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        Map<String,Object> map = new HashMap<>();
        map.put("user", user);
        map.put("roles", roles);
        map.put("permissions", permissions);
        return R.ok(map);
    }

    @ApiOperation("获取当前登陆用户菜单列表")
    @GetMapping("/getMenuInfo")
    public R<QueryMenuInfo> getMenuInfo(HttpServletRequest request){
        SysUser user = userService.selectUserById(SecurityUtils.getUserId());
        QueryMenuInfo info = permissionService.queryMenuByRoleId(user);
        return R.ok(info);
    }

    /**
     * 根据用户编号获取详细信息
     */
//    @RequiresPermissions("system:user:query")
    @GetMapping("/queryUserById")
    @ApiOperation(value = "根据用户ID获取详细信息")
    public R getInfo(@RequestParam(required = false) Long userId)
    {
        userService.checkUserDataScope(userId);
        Map<String,Object> map = new HashMap<>();
        List<SysRole> roles = roleService.selectRoleAll();
        map.put("roles",SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        map.put("posts",postService.selectPostAll());
        if (StringUtils.isNotNull(userId))
        {
            SysUser sysUser = userService.selectUserById(userId);
            map.put("user",sysUser);
            map.put("postIds",postService.selectPostListByUserId(userId));
            map.put("roleIds",sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return R.ok(map);
    }

    @GetMapping("/getUser/{userId}")
    @ApiOperation(value = "获取用户信息")
    public R getUser(@PathVariable Long userId){
        return R.ok(userService.selectUserById(userId));
    }

    /**
     * 新增用户
     */
//    @RequiresPermissions("system:user:add")
    @Log(title = "新增用户", businessType = BusinessType.INSERT)
    @PostMapping(value = "/add")
    @ApiOperation(value = "新增用户")
    public R add(@Validated @RequestBody CreateUserRq rq)
    {
        deptService.checkDeptDataScope(rq.getDeptId());
        roleService.checkRoleDataScope(rq.getRoleIds());
        if (!userService.checkUserName(rq.getUserName()))
        {
            return R.fail("新增用户'" + rq.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(rq.getPhone()) && !userService.checkPhone(rq.getPhone()))
        {
            return R.fail("新增用户'" + rq.getUserName() + "'失败，手机号码已存在");
        }
//        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(rq.get))
//        {
//            return R.fail("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
//        }
        rq.setPassword(SecurityUtils.encryptPassword(rq.getPassword()));
        return userService.createUser(rq);
    }

    /**
     * 修改用户
     */
//    @RequiresPermissions("system:user:edit")
    @Log(title = "修改用户", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/update")
    @ApiOperation(value = "修改用户")
    public R edit(@Validated @RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        deptService.checkDeptDataScope(user.getDeptId());
        roleService.checkRoleDataScope(user.getRoleIds());
        if (!userService.checkUserNameUnique(user))
        {
            return R.fail("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return R.fail("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return R.fail("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        return R.ok(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
//    @RequiresPermissions("system:user:remove")
    @Log(title = "删除用户", businessType = BusinessType.DELETE)
    @GetMapping("/delete/{userIds}")
    @ApiOperation(value = "删除用户")
    public R remove(@PathVariable Long[] userIds)
    {
        if (ArrayUtils.contains(userIds, SecurityUtils.getUserId()))
        {
            return R.fail("当前用户不能删除");
        }
        return R.ok(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
//    @RequiresPermissions("system:user:edit")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd")
    @ApiOperation(value = "重置密码")
    public R resetPwd(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return R.ok(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
//    @RequiresPermissions("system:user:edit")
    @Log(title = "修改用户状态", businessType = BusinessType.UPDATE)
    @GetMapping("/changeStatus")
    @ApiOperation(value = "状态修改")
    public R changeStatus(@RequestParam Long userId,@RequestParam String status)
    {
//        userService.checkUserAllowed(user);
//        userService.checkUserDataScope(user.getUserId());
//        user.setUpdateBy(SecurityUtils.getUsername());
        return R.ok(userService.updateUserStatus(userId,status));
    }

    /**
     * 根据用户编号获取授权角色
     */
//    @RequiresPermissions("system:user:query")
    @GetMapping("/authRole/{userId}")
    @ApiOperation(value = "根据用户编号获取授权角色")
    public R authRole(@PathVariable("userId") Long userId)
    {
        Map<String,Object> map = new HashMap<>();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        map.put("user",user);
        map.put("roles",SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return R.ok(map);
    }

    /**
     * 用户授权角色
     */
//    @RequiresPermissions("system:user:edit")
    @Log(title = "用户授权角色", businessType = BusinessType.GRANT)
    @GetMapping("/authRole")
    @ApiOperation(value = "用户授权角色")
    public R insertAuthRole(@RequestParam(value = "userId") Long userId, @RequestParam(value = "roleIds") Long[] roleIds)
    {
        userService.checkUserDataScope(userId);
        roleService.checkRoleDataScope(roleIds);
        userService.insertUserAuth(userId, roleIds);
        return R.ok();
    }

    /**
     * 获取部门树列表
     */
//    @RequiresPermissions("system:user:list")
    @GetMapping("/deptTree")
    @ApiOperation(value = "获取部门树列表")
    public R deptTree(SysDept dept)
    {
        return R.ok(deptService.selectDeptTreeList(dept));
    }

    @ApiOperation("根据组织ID查询用户列表")
    @GetMapping("/query/userList/byDeptId")
    public R<List<SysUser>> queryUserListByDeptId(@RequestParam Long deptId){
        List<SysUser> userList = userService.queryUserListByDeptId(deptId);
        return R.ok(userList);
    }

    @ApiOperation("商家端--部门列表")
    @GetMapping("/merchantDeptList")
    public R<List<SysDept>> merchantDeptList(){
        List<SysDept> sysDepts = deptService.selectDeptListByMerchantId();
        return R.ok(sysDepts);
    }

    @ApiOperation("商家端--新增部门信息")
    @PostMapping("/addMerchantDept")
    public R addMerchantDept(@RequestBody MerchantDeptPo merchantDeptPo){
        return R.ok(deptService.addMerchantDept(merchantDeptPo));
    }

}
